<!--
  * 工时功能
  *
  * @Author:    yjg
  * @Date:      2024-09-09 11:02:13
  * @Copyright  v1.0
-->
<template>
    <!-- 查询表单form begin -->
    <a-form class="smart-query-form">
        <a-row class="smart-query-form-row">
			<a-form-item label="部门" name="departmentId" class="smart-query-form-item">
				<DepartmentTreeSelect ref="departmentTreeSelect" width="180px" :init="false" v-model:value="departmentId" @change="departmentChange"/>
			</a-form-item>
			<a-form-item label="人员选择" name="memberIdList" class="smart-query-form-item" >
			  <a-select mode="multiple" v-model:value="checkedMemberId" style="width: 200px" @change="employeeChange" optionFilterProp="title" placeholder="请人员选择">
			  <a-select-option v-for="item in memberList" :key="item.loginName"  :title="item.loginName">{{ item.actualName }}</a-select-option>
			  </a-select>
			</a-form-item>
			<a-form-item label="班别类型" name="banbieType" class="smart-query-form-item">
			  <DictSelect key-code="BANBIE_TYPE" v-model:value="queryForm.banbieType" width="120px" />
			</a-form-item>
			<a-form-item label="加班类型" name="banbieType" class="smart-query-form-item">
			  <DictSelect key-code="OVERTIM_TYPE" v-model:value="queryForm.overtimeType" width="120px" />
			</a-form-item>
			<a-form-item label="工作时间" class="smart-query-form-item">
			  <a-space direction="vertical" :size="12">
			    <a-range-picker v-model:value="searchDate" :presets="defaultTimeRanges" @change="dateChange" />
			  </a-space>
			</a-form-item>
            <a-form-item class="smart-query-form-item">
                <a-button type="primary" @click="queryData">
                    <template #icon>
                        <SearchOutlined />
                    </template>
                    查询
                </a-button>
                <a-button @click="resetQuery" class="smart-margin-left10">
                    <template #icon>
                        <ReloadOutlined />
                    </template>
                    重置
                </a-button>
            </a-form-item>
        </a-row>
    </a-form>
    <!-- 查询表单form end -->

    <a-card size="small" :bordered="false" :hoverable="true">
        <!-- 表格操作行 begin -->
        <a-row class="smart-table-btn-block">
            <div class="smart-table-operate-block">
                <a-button @click="showForm" type="primary" v-privilege="'workinghours:add'">
                    <template #icon>
                        <PlusOutlined />
                    </template>
                    新建
                </a-button>
				<!-- <a-button @click="showFormPreview" type="primary" v-privilege="'workinghours:preview'">
				    <template >
				        <PlusOutlined />
				    </template>
				    预览
				</a-button> -->
				<!-- v-privilege="'workinghours:printPDF'" -->
				<a-button @click="printPDF" type="primary" > 
				    <template >
				        <PlusOutlined />
				    </template>
				    打印
				</a-button>
                <a-button @click="confirmBatchDelete" danger :disabled="selectedRowKeyList.length === 0" v-privilege="'workinghours:delete'">
                    <template #icon>
                        <DeleteOutlined />
                    </template>
                    批量删除
                </a-button>
				
            </div>
            <div class="smart-table-setting-block">
                <TableOperator v-model="columns" :tableId="null" :refresh="queryData" />
            </div>
        </a-row>
        <!-- 表格操作行 end -->

        <!-- 表格 begin -->
        <a-table
                size="small"
                :dataSource="tableData"
                :columns="columns"
                rowKey="workingHoursId"
                bordered
                :loading="tableLoading"
                :pagination="false"
                :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
        >
            <template #bodyCell="{ text, record, column, index }">
				<span v-if="column.dataIndex === 'serialNumber'">{{ index + 1 }}</span>
				<template v-if="column.dataIndex === 'banbieType'">
				  <span>{{ text && text.length > 0 ? text[0].valueName : '' }}</span>
				</template>
				<template v-if="column.dataIndex === 'overtimeType'">
				  <span>{{ text && text.length > 0 ? text[0].valueName : '' }}</span>
				</template>
				<template v-if="column.dataIndex === 'allowFlag'">
				  <span>{{ text ==1 ? '审批通过' : (text ==2 ? '驳回':text ==3 ? '撤销' : (text ==2 ? '不通过':'')) }}</span>
				</template>
                <template v-if="column.dataIndex === 'action'">
                    <div class="smart-table-operate">
						<a-button @click="onDelete(record)" v-if="record.allowFlag != 1" danger type="link" v-privilege="'workinghours:batchDelete'">删除</a-button>
                        <a-button  type="link" v-privilege="'workinghours:update'"
						v-if="record.allowFlag == 1"
						>已审批</a-button>
						<a-button @click="showForm(record)" type="link" v-privilege="'workinghours:update'"
						v-if="record.allowFlag == 2 || record.allowFlag ==0 "
						>编辑</a-button>
                    </div>
                </template>
            </template>
        </a-table>
        <!-- 表格 end -->

        <div class="smart-query-table-page">
            <a-pagination
                    showSizeChanger
                    showQuickJumper
                    show-less-items
                    :pageSizeOptions="PAGE_SIZE_OPTIONS"
                    :defaultPageSize="queryForm.pageSize"
                    v-model:current="queryForm.pageNum"
                    v-model:pageSize="queryForm.pageSize"
                    :total="total"
                    @change="queryData"
                    @showSizeChange="queryData"
                    :show-total="(total) => `共${total}条`"
            />
        </div>
        <WorkingHoursForm  ref="formRef" @reloadList="queryData"/>		
		<WorkingHoursFormPreview  ref="formPreviewRef"/>
		
		<div class="all" id="pdf" style="display:none;">
			<a-row class="smart-table-btn-block" style="margin-bottom: 0px;">
				<div class="smart-table-operate-block" style="font-size: 15px;margin-left: 10px;">
					部门:{{deptNames}}
				</div>
				<div class="smart-table-setting-block" style="font-size: 15px;margin-right: 10px;">
					工时时间：{{overtimeData}}
				</div>
			</a-row>
			<div class="table" ref="contentTable">
			</div>
			<div class="footer" style="display: flex;width:100%;height: 145px;">
				<div style="font-size:14px;font-family:500;width: 50%;">
					当日
					<div>
						<div style="float: left;margin-right:30px;">
							<div style="border: 1px solid #000;padding:5px;">班/组责任者</div>
							<div style="border-bottom: 1px solid #000;border-left: 1px solid #000;border-right: 1px solid #000;height: 40px;"></div>
							<div style="margin-top:10px;text-align:center;">(申请)</div>
						</div>
						
						<div style="float: left;margin-right:30px;">
							<div style="border: 1px solid #000;padding:5px;">部门责任者</div>
							<div style="border-bottom: 1px solid #000;border-left: 1px solid #000;border-right: 1px solid #000;height: 40px;"></div>
							<div style="margin-top:10px;text-align:center;">(批准)</div>
						</div>
						<div style="float: left;margin-right:30px;">
							<div style="border: 1px solid #000;padding:5px 20px;">总经办</div>
							<div style="border-bottom: 1px solid #000;border-left: 1px solid #000;border-right: 1px solid #000;height: 40px;"></div>
							<div style="margin-top:10px;text-align:center;">(批准)</div>
						</div>
					</div>
				</div>
				<div style="font-size:14px;font-family:500">
					次日
					<div>
						<div style="float: left;margin-right:30px;margin-left: 35;">
							<div style="border: 1px solid #000;padding:5px;">班/组责任者</div>
							<div style="border-bottom: 1px solid #000;border-left: 1px solid #000;border-right: 1px solid #000;height: 40px;"></div>
							<div style="margin-top:10px;text-align:center;">(实际时间记入)</div>
						</div>
						<div style="float: left;margin-right:30px;">
							<div style="border: 1px solid #000;padding:5px;">部门责任者</div>
							<div style="border-bottom: 1px solid #000;border-left: 1px solid #000;border-right: 1px solid #000;height: 40px;"></div>
							<div style="margin-top:10px;text-align:center;">(确认)</div>
						</div>
						<div style="float: left;">
							<div style="border: 1px solid #000;padding:5px 20px;">行政部</div>
							<div style="border-bottom: 1px solid #000;border-left: 1px solid #000;border-right: 1px solid #000;height: 40px;"></div>
							<div style="margin-top:10px;text-align:center;">(审核)</div>
						</div>
					</div>
				</div>
			</div>
			<div class="botton_print">
				打印日期：{{printData}}
			</div>
		</div>
    </a-card>
</template>
<script setup>
    import { reactive, ref, onMounted } from 'vue';
    import { message, Modal } from 'ant-design-vue';
    import { SmartLoading } from '/@/components/framework/smart-loading';
    import { workingHoursApi } from '/@/api/business/working-hours/working-hours-api';
    import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
    import { smartSentry } from '/@/lib/smart-sentry';
    import TableOperator from '/@/components/support/table-operator/index.vue';
    import WorkingHoursForm from './components/working-hours-form.vue';
	import WorkingHoursFormPreview from './components/working-hours-form-preview.vue';
	import DictSelect from '/@/components/support/dict-select/index.vue';
	import { defaultTimeRanges } from '/@/lib/default-time-ranges';
	import { employeeApi } from '/@/api/system/employee-api';
	import DepartmentTreeSelect from '/@/components/system/department-tree-select/department.vue';
	import printJS from 'print-js'
	import { Solar } from 'lunar-javascript';
    // ---------------------------- 表格列 ----------------------------

    const columns = ref([
		{
		  title: '序号',
		  dataIndex: 'serialNumber', // 这个dataIndex仅作为标识，不对应实际数据字段
		  width: '50px', // 可以自定义宽度
		  scopedSlots: { customRender: 'bodyCell' }, // 对应模板中的具名插槽
		},
		{
		    title: '工号',
		    dataIndex: 'jobNumber',
		    ellipsis: true,
			width: '70px', // 可以自定义宽度
			sorter: {
			  compare: (a, b) => a.jobNumber - b.jobNumber,
			  multiple: 3,
			},
		},
        {
            title: '姓名',
            dataIndex: 'name',
            ellipsis: true,
        },
        {
            title: '部门名称',
            dataIndex: 'deptName',
            ellipsis: true,
        },
        {
            title: '工作日期',
            dataIndex: 'overtimeData',
        },
        {
            title: '班别类型',
            dataIndex: 'banbieType',
        },
        {
            title: '加班类型',
            dataIndex: 'overtimeType',
            ellipsis: true,
        },
        {
            title: '建议加班1',
            dataIndex: 'timeparams1',
            ellipsis: true,
        },
        {
            title: '建议加班2',
            dataIndex: 'timeparams2',
            ellipsis: true,
        },
        {
            title: '建议加班3',
            dataIndex: 'timeparams3',
            ellipsis: true,
        },
        {
            title: '时数',
            dataIndex: 'overtimeNumber2',
            ellipsis: true,
			width:80,
			
        },
        {
            title: '加班原因',
            dataIndex: 'overtimeResult',
            ellipsis: true,
        },
        {
            title: '审批状态',
            dataIndex: 'allowFlag',
            ellipsis: true,
        },
        {
            title: '审批时间',
            dataIndex: 'allowTime',
            ellipsis: true,
        },
        {
            title: '审批人',
            dataIndex: 'allowMember',
            ellipsis: true,
			width: 100,
        },
        {
            title: '操作',
            dataIndex: 'action',
            fixed: 'right',
            width: 90,
        },
    ]);

    // ---------------------------- 查询数据表单和方法 ----------------------------

    const queryFormState = {
        pageNum: 1,
        pageSize: 15,
		overtimeFlag: 0,
		endTime: null,
		startTime: null,
		banbieType: null,
		overtimeType: null,
		departmentIds: null,
		checkedMemberNumbers: null,
		overtimeData: null,
    };
    // 查询表单form
    const queryForm = reactive({ ...queryFormState });
    // 表格加载loading
    const tableLoading = ref(false);
    // 表格数据
    const tableData = ref([]);
    // 总数
    const total = ref(0);
	// 日期选择
	let searchDate = ref();
	// 部门选择
	let departmentId = ref();
	//人员列表
	const memberList = ref([]); 
	//选中人员列表
	const checkedMemberId = ref([]);
	
	let solar = Solar.fromDate(new Date());
	let day = solar.toString();
	const printData = ref(day);  //打印日期
	
	const overtimeData = ref(day);
	
	const deptNameArr = ref([]);
	const deptNames = ref('');
	
	const contentTable = ref(null);

    // 重置查询条件
    function resetQuery() {
		searchDate.value = [];
		departmentId.value = [];
		checkedMemberId.value = [];
        let pageSize = queryForm.pageSize;
        Object.assign(queryForm, queryFormState);
        queryForm.pageSize = pageSize;
        queryData();
    }
	
	//部门选择
	function departmentChange(departments,departmentString){
	   deptNames.value = [];
	   queryForm.departmentIds = departments
	   for(let i = 0 ; i < departmentString.length;i++){
	       deptNames.value +=departmentString[i]+','
	   }
	   deptNames.value = deptNames.value.substring(0,deptNames.value.lastIndexOf(","))
	}
	//人员选择
	function employeeChange(employees,employeesString){
		queryForm.checkedMemberNumbers = employees;
	}

	function dateChange(dates, dateStrings) {
	  queryForm.startTime = dateStrings[0];
	  queryForm.endTime = dateStrings[1];
	  overtimeData.value = dateStrings[0];
	}
	
	async function handleEmployee(){
		  try{
			memberList.value = null;
			let queryResult = await employeeApi.queryAll()
			memberList.value = queryResult.data
		  }catch(e){
			  smartSentry.captureError(e);
		  } finally {
	        
	    }
	}
	

    // 查询数据
    async function queryData() {
		handleEmployee();
		if((queryForm.banbieType+1) == '1'){
			queryForm.banbieType = null;
		}
		if((queryForm.overtimeType+1) == '1'){
			queryForm.overtimeType = null;
		}
        tableLoading.value = true;
        try {
            let queryResult = await workingHoursApi.queryPage(queryForm);
            tableData.value = queryResult.data.list;
            total.value = queryResult.data.total;
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            tableLoading.value = false;
        }
    }


    onMounted(queryData);
	
	// ---------------------------- 预览 ----------------------------
	
	const formPreviewRef = ref();
	
	function showFormPreview(data) {
	    formPreviewRef.value.show(data);
	}

    // ---------------------------- 添加/修改 ----------------------------
    const formRef = ref();

    function showForm(data) {
        formRef.value.show(data);
    }

    // ---------------------------- 单个删除 ----------------------------
	
    //确认删除
    function onDelete(data){
        Modal.confirm({
            title: '提示',
            content: '确定要删除选项吗?',
            okText: '删除',
            okType: 'danger',
            onOk() {
                requestDelete(data);
            },
            cancelText: '取消',
            onCancel() {},
        });
    }

    //请求删除
    async function requestDelete(data){
        SmartLoading.show();
        try {
            let deleteForm = {
                goodsIdList: selectedRowKeyList.value,
            };
            await workingHoursApi.delete(data.workingHoursId);
            message.success('删除成功');
            queryData();
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }

    // ---------------------------- 批量删除 ----------------------------

    // 选择表格行
    const selectedRowKeyList = ref([]);

    function onSelectChange(selectedRowKeys) {	
        selectedRowKeyList.value = selectedRowKeys;
    }

    // 批量删除
    function confirmBatchDelete() {
        Modal.confirm({
            title: '提示',
            content: '确定要批量删除这些数据吗?',
            okText: '删除',
            okType: 'danger',
            onOk() {
                requestBatchDelete();
            },
            cancelText: '取消',
            onCancel() {},
        });
    }

    //请求批量删除
    async function requestBatchDelete() {
        try {
            SmartLoading.show();
            await workingHoursApi.batchDelete(selectedRowKeyList.value);
            message.success('删除成功');
            queryData();
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }
	
	//------------------------------------打印--------------------------------------
	// 查询数据
	async function printPDF() { 
		if(queryForm.departmentIds === null || queryForm.departmentIds.length ==0){
			message.error('请选择部门!');
			return
		}
		queryForm.overtimeData = queryForm.startTime
		let Table = document.querySelector(".table")
		try {
			let queryResult = await workingHoursApi.selectPdfDown(queryForm)
			Table.innerHTML = ""
			let str = ""
			str += "<div class='table-row' style ='display: table-row;'>"
			str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color:#000;width:40px;text-align:center;vertical-align: middle;'>序号</div>"
			str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color:#000;text-align:center;width:50px;vertical-align: middle;'>工号</div>"
			str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color:#000;text-align:center;width:60px;vertical-align: middle;'>姓名</div>"
			str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color:#000;text-align:center;width:40px;vertical-align: middle;'>班别</div>"
			str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color:#000;text-align:center;width:45px;vertical-align: middle;'>加班时间段</div>"
			str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color:#000;text-align:center;width:45px;vertical-align: middle;'>加班时间段2</div>"
			str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color:#000;text-align:center;width:45px;vertical-align: middle;'>加班时间段3</div>"
			str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color:#000;text-align:center;width:45px;vertical-align: middle;'>加班时数(H)</div>"
			str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color:#000;text-align:center;width:40px;vertical-align: middle;'>加班类型</div>"
			str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color:#000;text-align:center;width:45px;vertical-align: middle;'>实际时数(H)</div>"
			str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color:#000;text-align:center;width:35px;vertical-align:middle;'>本月累计</div>"
			str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color:#000;text-align:center;width:80px;vertical-align:middle;'>本人签字</div>"
			str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color:#000;text-align:center;vertical-align:middle;'>备注</div>"
			str += "</div>"
			let index = 1;
			for(let item of queryResult.data){
				deptNameArr.value.push(item.deptName);
				str += "<div class='table-row' style ='display: table-row;'>"
				str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color: #000;width:40px;text-align:center;vertical-align: middle;'>"+(index++)+"</div>"
				str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color: #000;text-align:center;width:50px;vertical-align: middle;'>"+item.jobNumber+"</div>"
				str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color: #000;text-align:center;width:60px;vertical-align: middle;'>"+item.name+"</div>"
				str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color: #000;text-align:center;width:40px;vertical-align: middle;'>"+item.banbieType+"</div>"
				str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color: #000;text-align:center;width:45px;vertical-align: middle;'>"+item.timeparams1+"</div>"
				str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color: #000;text-align:center;width:45px;vertical-align: middle;'>"+item.timeparams2+"</div>"
				str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color: #000;text-align:center;width:45px;vertical-align: middle;'>"+item.timeparams3+"</div>"
				str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color: #000;text-align:center;width:45px;vertical-align: middle;'>"+item.overtimeNum+"</div>"
				str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color: #000;text-align:center;width:40px;vertical-align: middle;'>"+item.overtimeType+"</div>"
				str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color: #000;text-align:center;width:45px;vertical-align: middle;'>"+item.overtimeNum+"</div>"
				str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color: #000;text-align:center;width:35px;vertical-align: middle;'>"+item.totalNum+"</div>"
				str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color: #000;text-align:center;width:80px;vertical-align: middle;'></div>"
				str += "<div class='table-cell' style = 'display: table-cell;border: 1px solid #000;color: #000;font-size:12px'>"+item.overtimeResult+"</div>"		
				str += "</div>"
			}
			Table.innerHTML = str;
		} catch (e) {
			smartSentry.captureError(e);
		} finally {
		
		}
		
		
		var printFrom = document.getElementById('pdf')
		printFrom.style.display = 'block'
		
		const rect = contentTable.value.getBoundingClientRect();
		console.log(`宽度: ${rect.width}, 高度: ${rect.height}`);
		console.log(Math.ceil(rect.height/880)*1020);
		document.getElementById('pdf').style.height= Math.ceil(rect.height/880)*1020+'px';
		
		setTimeout(() => {
			printFrom.style.display = 'none'
		}, 2000)
		//print.js的onPrintDialogClose事件触发失效,在打印事件触发之前，添加派发一个focus聚焦事件，然后点击取消或打印，清除focus事件。
		let focuser = setInterval(
			() => window.dispatchEvent(new Event('focus')),
			500
		)
		
		printJS({
			printable: 'pdf', // 'printFrom', // 标签元素id
			type: 'html',
			header: '加班人员名单', // '表单',
			headerStyle: 'text-align:center;width:100%; ',
			targetStyles: ['*'],
			font_size: '9pt',
		//	style: '@page {margin:0 10mm;} ', // 可选-打印时去掉眉页眉尾
			style: '@page {size: auto;margin:10mm;} ', // 可选-打印时保留眉页眉尾
			
			ignoreElements: ['no-print'] || [], // ['no-print']
			properties: null,
			//打印完成或关闭打印的事件
			onPrintDialogClose: () => {
				//取消打印回调
				//清除focus事件
				clearInterval(focuser)
				printFrom.style.display = 'none'
			}
		})
	}
	
</script>

<style scoped>
.all {
	width: 710px;
	/* height: 1090px; */
	height: 1020px;
	background-color: white;
	margin: 10px auto;
	overflow: auto;
	float: right;
	position: relative;
}

.table {
	display: table;
	width: 100%;
	border-spacing: 0;
	border-collapse: collapse;
	line-height:20px;
}

.footer{
	position: absolute;
	bottom: 0px;
}

.botton_print{
	position: absolute;
	bottom: 0px;
	width: 100%;
	text-align: right;
}
</style>


